package day14;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client2 {
    static volatile boolean isEsc;//false默认 没有退出
    public static void main(String[] args) throws IOException {
        Socket client=new Socket("192.168.9.11",9999);
        OutputStream os=client.getOutputStream();//写入
        Scanner sc=new Scanner(System.in);//读取控制台的数据
        //缺少一个向服务器 读取收据 由于山后面的肚子饿和监听服务端的数据
        //是相互独立的 所有也是一个线程
        new ClientThread2(client).start();
        System.out.println("请输入姓名:");
        String name=sc.nextLine();
        while (true){
            //sc.next();
            System.out.println("你要说啥？按esc可退出");
            String msg=sc.nextLine();
            if(msg!=null){
                if(msg.contains("esc")){
                    os.write((name+"退出聊天室esc\n").getBytes());
                    isEsc=true;//标记已经退出了
                    break;
                }else{
                    os.write((name+"说:"+msg+"\n").getBytes());
                }
            }
        }
        os.close();
        client.close();
    }
}
class ClientThread2 extends Thread{
    Socket client;
    public ClientThread2(Socket client) {
        this.client = client;
    }
    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader
                    (client.getInputStream()));
            while (!Client2.isEsc){
                String msg=br.readLine();
                if(msg!=null){
                    System.out.println(msg);
                }
            }
        }catch (Exception e){

        }
    }
}